<template>
    <div>
        <div class="container">

            <div class="table_btn">

                <label class="table-label">字典名称:</label>
                <el-input v-model="query.dictName"  placeholder="字典名称" class="menu-input" clearable></el-input>

                <label class="table-label">字典类型:</label>
                <el-input v-model="query.dictType"  placeholder="字典类型" class="menu-input" clearable></el-input>

                <label class="table-label">字典状态:</label>
                <el-select class="menu-input" v-model="query.status" placeholder="请选择">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>

                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>

                <el-button type="default" icon="el-icon-refresh" @click="searchReset">重置</el-button>

            </div>
            <div class="table_btn">
                <el-button type="success" icon="el-icon-edit" @click="addUser($event)">添加</el-button>
                <el-button type="danger" icon="el-icon-delete"  @click="allDelete()">批量删除</el-button>

            </div>
            <div class="box_table">
                <el-table
                        :data="tableData"
                        border
                        @selection-change="handleSelectionChange"
                        style="width: 100%">

                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>

                    <el-table-column
                            prop="dict_id"
                            label="字典主键"
                            width="80">
                    </el-table-column>

                    <el-table-column
                            prop="dict_name"
                            label="字典名称"
                            width="180">
                    </el-table-column>

                    <el-table-column
                            prop="dict_type"
                            label="字典类型"
                            width="180">
                    </el-table-column>

                    <el-table-column
                            prop="status"
                            label="状态"
                            width="100">
                        <template slot-scope="scope">
                            <el-tag
                                    :type="scope.row.status === 1 ? 'primary' : 'success'"
                                    disable-transitions>{{scope.row.status===1?'正常':'禁用'}}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column
                            prop="remark"
                            label="备注"
                            width="250">
                    </el-table-column>

                    <el-table-column
                            prop="create_time"
                            label="创建时间"
                            width="180">
                    </el-table-column>

                    <el-table-column label="操作" width="300">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    icon="el-icon-edit"
                                    type="primary"
                                    @click="handleEdit(scope.$index, scope.row)">
                                编辑
                            </el-button>

                            <el-button
                                    size="mini"
                                    icon="el-icon-s-grid"
                                    type="default"
                                    @click="handleDetails(scope.$index, scope.row)">
                                列表
                            </el-button>

                            <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.$index, scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :total="pageTotal"
                        :current-page.sync="currentPage"
                        :page-size="pageSize"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!--添加-->
        <el-dialog title="添加管类型" :visible.sync="dialogFormVisible"  width="35%">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px">

                <el-form-item label="字典名称" prop="dictName"  placeholder="请输入字典名称">
                    <el-input v-model="form.dictName"></el-input>
                </el-form-item>

                <el-form-item label="字典类型" prop="dictType"  placeholder="请输入字典类型">
                    <el-input v-model="form.dictType"></el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="form.status"
                               active-text="正常"
                               inactive-text="停用"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>


                <el-form-item label="备注" prop="remark">
                    <el-input  type="textarea"
                               placeholder="请输入备注"
                               :rows="2"
                               v-model="form.remark">
                    </el-input>
                </el-form-item>


                <el-form-item>
                    <el-button
                            type="primary"
                            @click="submitForm('form')"
                            :loading="addLoading">立即创建</el-button>
                    <el-button @click="resetForm('form')">重置</el-button>
                </el-form-item>

            </el-form>
        </el-dialog>

        <!-- 编辑 -->
        <el-dialog title="修改类型" :visible.sync="editDialog"  width="35%">
            <el-form :model="editForm"
                     :rules="editRules"
                     ref="edit_form"
                     label-width="100px">

                <el-form-item label="字典名称" prop="dictName"  placeholder="请输入字典名称">
                    <el-input v-model="editForm.dictName"></el-input>
                </el-form-item>

                <el-form-item label="字典类型" prop="dictType"  placeholder="请输入字典类型">
                    <el-input v-model="editForm.dictType"></el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="editForm.status"
                               active-text="正常"
                               inactive-text="停用"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>


                <el-form-item label="备注" prop="remark">
                    <el-input  type="textarea"
                               placeholder="请输入备注"
                               :rows="2"
                               v-model="editForm.remark">
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button
                            type="primary"
                            @click="edit('edit_form')"
                            :loading="editLoading">修 改</el-button>
                    <el-button @click="resetForm('edit_form')">重置</el-button>
                </el-form-item>

            </el-form>
        </el-dialog>

    </div>

</template>

<script>
    /**
     * 字典管理
     */
    import utils  from "@/utils/function"
    const  { request,checkMobile,dateFormat } = utils
    import Paging from "@/utils/paging"
    const paging = new Paging("/system/config/dict/list")

    export default {
        name: "dict",
        data() {
            //验证规则
            let addRules = {
                dictName: [
                    { required: true, message: '请输入字典名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                dictType: [
                    { required: true, message: '请输入字典类型', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ]
            }

            return {
                tableData: [],
                pageTotal: 0,
                multipleSelection:[],           //列表中checkbox选中的值
                dialogFormVisible:false,        //新增界面的显示
                query: {                        //查询数据
                    dictName:"",      //字典名称
                    dictType:"",        //字典类型
                    status:""           //字典状态
                },
                currentPage:1,
                pageSize:5,
                form: {
                    dictName: '',
                    dictType:'',
                    status:0,
                    remark:''
                },
                groupOpt:[],            //角色组
                options:[],             //字典状态列表
                rules: addRules,
                editRules:addRules,
                editForm:{
                    id:0,
                    dictName: '',
                    dictType:'',
                    status:0,
                    remark:''
                },     //当前编辑数据
                editDialog:false,        //编辑界面的显示
                addLoading:false,
                editLoading:false,
            }
        },
        created() {
            this.getUserList({page:1})
        },
        methods: {
            handlePageChange(val) {             //获取分页数据
                this.getUserList({page:val})
            },
            handleSearch(){             //查询
                paging.setQuery( _.cloneDeep(this.query) );
                this.handlePageChange(1)
                this.currentPage = 1
            },
            searchReset(){                  //查询重置
                _.forOwn(this.query,(value, key)=>{
                    this.$set(this.query,key,'')
                })
                this.handleSearch()
            },
            getUserList({page,query}){           //获取列表数据
                paging.request({page,query}).then(response=>{
                    let {code,data:{currentPage,total,list,searchStatus},msg} = response
                    if(code === 0){
                        this.pageTotal = total;
                        if(_.isArray(list) && list.length > 0){
                            this.tableData = list.map((value)=>{
                                value.create_time =  value.create_time ? dateFormat(value.create_time):''
                                value.remark_full = value.remark
                                value.remark = _.truncate(value.remark,{length:18});
                                return value
                            })
                        } else {
                            this.tableData = []
                        }

                        let arr = [];
                        _.forOwn(searchStatus, function(value, key) {
                            if(key !== ''){
                                arr.push({
                                    label:value,
                                    value:key
                                })
                            }
                        });

                        arr.unshift({
                            label:"全部",
                            value:""
                        })
                        this.options = arr
                    } else {
                        this.$message.error(msg);
                    }
                }).catch(error=>{
                    console.log(error);
                });
            },
            clearFilter() {
                this.$refs.filterTable.clearFilter();
            },
            filterTag(value, row) {
                return row.status === value;
            },
            handleSelectionChange(val) {        //列表中checkbox选中事件

                this.multipleSelection = val;
            },
            delete(ids){                        //删除管理员数据
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(_.isNumber(ids)){
                        ids = [ids]
                    }
                    if(!_.isArray(ids)){
                        return false;
                    }
                    request.loading().post("/system/config/dict/delete",{dictIds:ids}).then(response=>{
                        console.log(response);
                        let {code,data,msg} = response
                        if(code === 0){
                            this.getUserList({page:this.currentPage})
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        } else {
                            this.$message.error(msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    });

                }).catch((error) => {
                    console.log(error);
                    this.$message({
                        type: 'info',
                        message: '删除失败，请重试!'
                    });
                });
            },
            handleDelete(index,item){           //删除一条
                this.delete(item.dict_id);
            },
            allDelete(){                    //批量删除
                if(this.multipleSelection.length<1){
                    this.$message.error('选择要删除的内容');
                    return ;
                }
                this.delete(this.multipleSelection.map(value => value.dict_id))
            },
            addUser(){                      //添加
                this.dialogFormVisible = true
            },
            submitForm(form) {          //添加操作
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        const  form = this.form;
                        this.addLoading = true
                        request.post("/system/config/dict/add",form).then(response=>{
                            this.addLoading = false
                            let {code,data,msg}  = response
                            if(code === 0 ){
                                this.$message.success(msg);
                                this.dialogFormVisible = false
                                this.getUserList({page:1})
                                this.currentPage = 1
                                this.resetForm('form')
                            } else {
                                this.$message.error(msg);
                            }
                        }).catch(error=>{
                            console.log(error);
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {//重置
                this.$refs[formName].resetFields();
            },
            handleEdit(index,row){      //显示编辑页面
                request.loading().get('/system/config/dict/edit',{id:row.dict_id}).then(response=>{
                    let {code,data:{dict},msg} = response
                    if(code === 0){
                        let {dict_id,dict_name,dict_type,status,remark} = dict
                        this.editForm.dictId = dict_id || 0
                        this.editForm.dictName = dict_name || ""
                        this.editForm.dictType = dict_type|| ""
                        this.editForm.status = status || 0
                        this.editForm.remark = remark || ""
                        this.editDialog = true
                    }else {
                        this.$message.error(msg);
                    }
                })

            },
            edit(form){             //编辑提交
                this.$refs[form].validate((valid) => {
                    if (!valid) {
                        console.log('error submit!!');
                        return false;
                    }

                    this.editLoading = true
                    request.post("/system/config/dict/edit",this.editForm).then(response=>{
                        this.editLoading = false
                        let {code,data,msg}  = response
                        if(code === 0 ){
                            this.$message.success(msg);
                            this.editDialog = false
                            this.getUserList({page:this.currentPage})
                            this.resetForm('edit_form')
                        } else {
                            this.$message.error(msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    });
                })
            },
            handleDetails(index,item){          //跳转到详情页
                this.$router.push({
                    path: '/system/config/dictsub',
                    query: { dict_type : item.dict_type}
                })
            }

        }
    }
</script>

<style scoped lang="scss">
    .table-label{
        color:#606266;
        font-size:12px;
    }

    .menu-input {
        width:300px;
        margin:0 10px;
    }
</style>
